import { Component } from '@angular/core';
import { IonicPage,LoadingController, NavController, NavParams, PopoverController } from 'ionic-angular';
import {LocalStorProvider} from "../../providers/local-stor/local-stor";
import {ApiProvider} from "../../providers/api/api";
import {ExerciseAnswerPage} from "../exercise-answer/exercise-answer";

/**
 * Generated class for the ExercisesPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-exercises',
  templateUrl: 'exercises.html',
})
export class ExercisesPage {

  key = 'type';
  user_id;
  exerciseList;
  order=null;//排序

  searchText="";//搜索内容

  noMoreFlag=0;//加载更多标识（0—还有更多；1-没有更多）

  showSearchBar = false; // 搜索框显示隐藏

  activeNum = 0;

  /*筛选列表条件*/
  searchOptions={
    exerciseType:null,
    exerciseTypeStr:'类型',
    exerciseState:null,
    exerciseStateStr:'状态',
    exerciseSort:null,
    exerciseSortStr:'排序'
  };


  constructor(public navCtrl: NavController, public navParams: NavParams,
              public popover: PopoverController,private storage:LocalStorProvider,
              public http:ApiProvider,public loadingCtrl:LoadingController) {
  }

  // 题型筛选
  selectClick(operateType,value,text) {
    if (operateType == "type") {
      this.searchOptions.exerciseType = value;
      this.searchOptions.exerciseTypeStr=text;
      this.activeNum=0;
    }
    else if (operateType == "status")
    {
      this.searchOptions.exerciseState=value;
      this.searchOptions.exerciseStateStr=text;
      this.activeNum=0;
    }
    else
    {
      this.searchOptions.exerciseSort=value;
      this.searchOptions.exerciseSortStr=text;
      this.activeNum=0;
    }

    this.getExerciseList();
  }

  ionViewDidLoad() {
    this.storage.getKey("user_id").then(val=>{
      this.user_id=val;
    });

    //this.getExerciseList();
  }

  /**
   * 当进入页面时触发
   */
  ionViewDidEnter()
  {
    this.storage.getKey("user_id").then(val=>{
      this.user_id=val;
    });

    this.getExerciseList();
  }

  /**
   * 获取习题列表
   */
  getExerciseList()
  {
    let loading = this.loadingCtrl.create({
      content: '正在加载',
      showBackdrop: false,
      dismissOnPageChange:true
    });

    loading.present();
    this.http.post("/exercise/getProblemList.do",{studentId:this.user_id,createTime:'now',action:'up',
      exercise_type:this.searchOptions.exerciseType,start_answer:this.searchOptions.exerciseState,order:this.searchOptions.exerciseSort,exercise_name:this.searchText}).subscribe(item=>{
      if(item["Code"]=="11111111")
      {
        loading.dismiss();
        this.http.showToast(item["Message"],"bottom");
      }
      else
      {
        //console.log(item["probList"]);
        this.exerciseList=item["probList"];

        console.log(this.exerciseList);
        loading.dismiss();
      }
     }
    )
  }

  /**
   * 下拉刷新
   * @param refresher
   */
  doRefresh(refresher) {
    let loading = this.loadingCtrl.create({
      content: '刷新中...',
      showBackdrop: false,
      dismissOnPageChange:true
    });
    loading.present();

    this.http.post("/exercise/getProblemList.do",{studentId:this.user_id,createTime:'now',action:'up',
      exercise_type:this.searchOptions.exerciseType,start_answer:this.searchOptions.exerciseState,order:this.searchOptions.exerciseSort,
      exercise_name:this.searchText}).subscribe(item=>{
      if(item["Code"]=="11111111")
      {
        loading.dismiss();
        this.http.showToast(item["Message"],"bottom");
      }
      else
      {
        setTimeout(() => {
          this.exerciseList=item["probList"];
          refresher.complete();
          loading.dismiss();
        },2000);
      }
    });
  }

  /**
   * 加载更多
   * @param infiniteScroll
   */
  doInfinite(infiniteScroll)
  {
    if(this.noMoreFlag==1)
    {
      infiniteScroll.complete();
      return;
    }

    let lastTime;
    if(this.exerciseList.length>0)
      lastTime=this.exerciseList[this.exerciseList.length-1].create_time;
    else
      lastTime='now';

    this.http.post("/exercise/getProblemList.do",{studentId:this.user_id,createTime:lastTime,action:'up',
      exercise_type:this.searchOptions.exerciseType,start_answer:this.searchOptions.exerciseState,order:this.searchOptions.exerciseSort,
      exercise_name:this.searchText}).subscribe(item=>{
      if(item["Code"]=="11111111")
      {
        this.http.showToast(item["Message"],"bottom")
      }
      else
      {
        setTimeout(() => {
          if(item["probList"].length>0)
          {
            for(var i=0;i<item["probList"].length;i++)
            {
              this.exerciseList.push(item["probList"][i]);
            }
          }
          else
          {
            this.noMoreFlag=1;
          }
          infiniteScroll.complete();   //当数据请求完成调用
        },1000);
      }
    });
  }

  /**
   * 搜索
   * @param ev
   */
  search()
  {
    this.showSearchBar = !this.showSearchBar

    this.noMoreFlag=0;
/*    let loading = this.loadingCtrl.create({
      content: '正在加载',
      showBackdrop: false
    });
    loading.present();*/
    this.http.post("/exercise/getProblemList.do",{studentId:this.user_id,createTime:'now',action:'up',
      exercise_type:this.searchOptions.exerciseType,start_answer:this.searchOptions.exerciseState,order:this.searchOptions.exerciseSort,exercise_name:this.searchText}).subscribe(item=>{
        if(item["Code"]=="11111111")
        {
          //loading.dismiss();
          this.http.showToast(item["Message"],"bottom");
        }
        else
        {
          //console.log(item["probList"]);
          this.exerciseList=item["probList"];
          //loading.dismiss();
        }
      }
    )
  }

  /**
   * 资源查看
   * @param path 路径
   * @param title 标题
   * @param sourceId 资源id
   * @param sourceType 资源类型
   * @param source_id 资源id-教师id-资源类型拼接串
   * @param isCheck 是否下载，查看，或答题
   * @param num 习题索引
   * @param start_answer 是否开始答题，答题状态
   * @param start_time 课中习题开始答题时间
   * @constructor
   */
  ViewSource(title,sourceId,sourceType,num,start_answer,start_time,teacherId,unitId,classCourseId,classType,answer_type)
  {
    //习题
    //进入习题作答页面
    this.navCtrl.push(ExerciseAnswerPage,{exerciseType:sourceType,exerciseNo:(+num)+1,teacherId:teacherId,studentId:this.user_id,exerciseId:sourceId,
      unitId:unitId,classCourseId:classCourseId,classType:classType,start_answer:start_answer,start_time:start_time,answer_type:answer_type});
  }
}
